package com.zmj.sy.mom.srv.aps.service;


import com.zmj.sy.mom.srv.aps.bean.entity.mes.WorkDetailTask;

import com.zmj.sy.mom.srv.aps.bean.vo.work.WorkPartBatchEndReqVo;
import com.zmj.sy.mom.srv.aps.mapper.WorkDetailTaskMapper;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class WorkService {

    private final WorkDetailTaskMapper workDetailTaskMapper;

    @Transactional
    public void partBatchEnd(List<WorkPartBatchEndReqVo> reqList) {
        for (WorkPartBatchEndReqVo req : reqList) {
            List<WorkDetailTask> taskList = workDetailTaskMapper.lambdaQuery()
                    .eq(WorkDetailTask::getPlmid, req.getPlmId())
                    .eq(WorkDetailTask::getPhaseCode, req.getPhaseCode())
                    .eq(WorkDetailTask::getGroupCode, req.getGroupCode())
                    .eq(WorkDetailTask::getStatus, 3)
                    .list();

            if(taskList.isEmpty()){
                throw SyExceptionUtils.e("没有找到已开工的任务");
            }

            Integer reportCount = req.getTotalCount();

            if (reportCount == null || reportCount < 0) {
                throw SyExceptionUtils.e("报工数量不能小于0");
            }

            IntSummaryStatistics collect = taskList.stream().collect(Collectors.summarizingInt(WorkDetailTask::getTotalCount));
            long sum = collect.getSum();
            if(reportCount > sum){
                throw SyExceptionUtils.e("数量超了");
            }


            int kkk = reportCount;
            for (WorkDetailTask workDetailTask : taskList) {
                int currentTotal = 0;
                if(kkk > workDetailTask.getTotalCount()){
                    currentTotal = workDetailTask.getTotalCount();

                } else if(kkk < workDetailTask.getTotalCount()) {
                    currentTotal = kkk;
                } else {
                    currentTotal = kkk;
                }
                kkk = kkk - currentTotal;


//                partEnd(req, workDetailTask, );

            }




            
        }
    }


}
